//
//  BannerVM.swift
//  kxf
//
//  Created by Mac on 2024/3/9.
//

import Foundation
import CHIPageControl

class BannerVM: UIView {
    
    var selfHeight = kFitWidth(150)
    
    var controller = UIViewController()
    
    var isMainHot = false
    public var spinChainBlock: ((NSDictionary)->())?
    var remotePathGroup = NSArray()
    
    override init(frame:CGRect){
        super.init(frame: CGRect.init(x: 0, y: frame.origin.y, width: SCREEN_WIDHT, height: selfHeight))
        self.backgroundColor = .clear
        self.isUserInteractionEnabled = true
        initUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var cycleScrollView: ZKCycleScrollView = {
        let zhView = ZKCycleScrollView()//.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDHT, height: kFitWidth(150)))
        zhView.delegate = self //as ZKCycleScrollViewDelegate
        zhView.dataSource = self //as ZKCycleScrollViewDataSource
        addSubview(zhView)
        zhView.snp.makeConstraints { (frame) in
            frame.width.equalToSuperview()
            frame.height.equalTo(kFitWidth(150))
            frame.top.equalToSuperview()
        }
        zhView.isUserInteractionEnabled = true
        zhView.hidesPageControl = true
        zhView.itemZoomScale = 0.8
        zhView.isHidden = true
        zhView.itemSpacing = kFitWidth(-20)
        zhView.itemSize = CGSize(width: kFitWidth(360), height: kFitWidth(134))
        zhView.register(BannerCell.classForCoder(), forCellWithReuseIdentifier: "BannerCell")
        return zhView
    }()
    
    private var banner: GXBanner = {
        let frame: CGRect = CGRect(x: 0, y: kFitWidth(5), width: SCREEN_WIDHT, height: kFitWidth(140))
        return GXBanner(frame: frame, margin: kFitWidth(30), minScale: GXBanner.Scale(sx: 0.9, sy: 0.9))
    }()
    
    lazy var pageControlTopbanner: CHIPageControlPuya = {
        let zhView = CHIPageControlPuya()
        zhView.isHidden = true
        zhView.padding = 15.0
        zhView.inactiveTransparency = 1.0
        zhView.hidesForSinglePage = true
        zhView.radius = kFitWidth(5)
        zhView.tintColor = WHColor_RGB(r: 241, g: 181, b: 190 )
        zhView.currentPageTintColor = WHColor_RGB(r: 255, g: 83, b: 107 )
        zhView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
        
        return zhView
    }()
    lazy var bannerImgView : UIImageView = {
        let img = UIImageView()
        img.backgroundColor = WHColor_LineGray()
        img.isHidden = true
        img.layer.cornerRadius = kFitWidth(8)
        img.clipsToBounds = true
        img.isUserInteractionEnabled = true
        img.contentMode = .scaleAspectFit
        
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: #selector(bannerImgTap))
        img.addGestureRecognizer(tap)
        
        return img
    }()
}

extension BannerVM{
    func initUI(){
        addSubview(cycleScrollView)
//        addSubview(pageControlTopbanner)
        
        addSubview(self.banner)
        banner.backgroundColor = UIColor.clear
        banner.autoTimeInterval = 2.0
        banner.dataSource = self
        banner.delegate = self
//        banner.isShowPageControl = false
        banner.register(classCellType: BannerCell.self)
//        banner.reloadData()
        
        addSubview(bannerImgView)
        bannerImgView.snp.makeConstraints({ (frame) in
            frame.width.equalTo(kFitWidth(343))
            frame.height.equalTo(kFitWidth(126))
            frame.center.lessThanOrEqualToSuperview()
//            frame.bottom.equalTo(-kFitWidth(10))
        })
    }
    
    func setDataSource(dataSourceArr:NSArray){
//        if dataSourceArr.count == 0 {
//            return
//        }
//        remotePathGroup = dataSourceArr
        if dataSourceArr.count > 1{
            bannerImgView.isHidden = true
            banner.isHidden = false
            pageControlTopbanner.isHidden = false
            pageControlTopbanner.numberOfPages = self.remotePathGroup.count
            banner.reloadData()
        }else{
            bannerImgView.isHidden = false
            banner.isHidden = true
            pageControlTopbanner.isHidden = true
//            let dict = dataSourceArr[0] as? NSDictionary ?? [:]
//            let imgUrl = URL(string: (dict["pictureUrl"] as? String ?? "").addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
//            bannerImgView.kf.setImage(with: imgUrl, placeholder: UIImage.init(named: "main_banner_img"), options: [.transition(.fade(0.2))])
            bannerImgView.setImgLocal(imgName: "main_banner_img")
        }
    }
}

extension BannerVM{
    func jumpController(dict:NSDictionary){
        
    }
}

extension BannerVM: GXBannerDataSource, GXBannerDelegate {
    @objc func bannerImgTap(){
//        let dict = remotePathGroup[0] as? NSDictionary ?? [:]
//        jumpController(dict: dict)
    }
    // MARK: - GXBannerDataSource
    func numberOfItems() -> Int {
        return remotePathGroup.count
    }
    
    // MARK: - GXBannerDelegate

    func banner(_ banner: GXBanner, didSelectItemAt indexPath: IndexPath) {
        NSLog("didSelectItemAt %d", indexPath.row)
//        let dict:NSDictionary = remotePathGroup[indexPath.row] as! NSDictionary
//        DLLog(message: "index  \(indexPath.row) --> \(dict)")
//        jumpController(dict: dict)
    }
    func banner(_ banner: GXBanner, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: BannerCell = banner.dequeueReusableCell(for: indexPath)
        cell.contentView.layer.masksToBounds = true
        cell.contentView.layer.cornerRadius = 10
        cell.contentView.backgroundColor = UIColor.clear
        
//        DLLog(message: "cellForItemAt indexPath:\(indexPath)")
//        DLLog(message: "cellForItemAt indexPath.row:\(indexPath.row)")
        
        
        if indexPath.row > remotePathGroup.count-1 {
            let item:NSDictionary = remotePathGroup[remotePathGroup.count-1] as! NSDictionary
            cell.imageUrl = item["pictureUrl"] as! String
            return cell
        }
        
        let item:NSDictionary = remotePathGroup[indexPath.row] as! NSDictionary
        cell.imageUrl = item["pictureUrl"] as! String
        pageControlTopbanner.progress = Double(indexPath.row)
        
        return cell
    }

}

extension BannerVM:ZKCycleScrollViewDelegate,ZKCycleScrollViewDataSource{
    func numberOfItems(in cycleScrollView: ZKCycleScrollView) -> Int {
        return remotePathGroup.count
    }
        
    func cycleScrollView(_ cycleScrollView: ZKCycleScrollView, cellForItemAt index: Int) -> ZKCycleScrollViewCell {
        let cell = cycleScrollView.dequeueReusableCell(withReuseIdentifier: "BannerCell", for: index) as! BannerCell
        let item:NSDictionary = remotePathGroup[index] as! NSDictionary
        
        cell.imageUrl = item["pictureUrl"] as! String
        return cell
    }
    
    func cycleScrollViewDidScroll(_ cycleScrollView: ZKCycleScrollView, progress: Double) {
        pageControlTopbanner.progress = progress
    }
    
    func cycleScrollView(_ cycleScrollView: ZKCycleScrollView, didSelectItemAt index: Int) {
//        let dict:NSDictionary = remotePathGroup[index] as! NSDictionary
//        DLLog(message: "index  \(index) --> \(dict)")
//        jumpController(dict: dict)
    }
}
 
